/*
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * This file is a part of the CANN Open Software.
 * Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */

#include <cstring>

#include "../../../common/data_utils.h"
#include "kernel_tiling/kernel_tiling.h"
#include "tiling/platform/platform_ascendc.h"
#include "../testcase_params.h"
#include "matmul_a2_b2_share_custom_tiling.h"
#ifndef ASCENDC_CPU_DEBUG
#include "acl/acl.h"
#else
#include "tikicpulib.h"
#endif

namespace MatmulCustomMian {
int64_t CompareResult(void* outputData, const int64_t outSize, const std::string goldenFile)
{
    void* goldenData;
#ifdef ASCENDC_CPU_DEBUG
    goldenData = (uint8_t*)AscendC::GmAlloc(outSize);
#else
    CHECK_ACL(aclrtMallocHost((void**)(&goldenData), outSize));
#endif
    size_t goldenSize = outSize;
    bool ret = ReadFile(goldenFile, goldenSize, goldenData, goldenSize);
    if (ret) {
        printf("ReadFile golden success!\n");
    } else {
#ifdef ASCENDC_CPU_DEBUG
        AscendC::GmFree((void*)goldenData);
#else
        CHECK_ACL(aclrtFreeHost(goldenData));
#endif
        return 1;
    }
    constexpr float EPS = 1e-4;
    int64_t wrongNum = 0;
    int64_t maxPrintNums = 10;
    for (int i = 0; i < outSize / sizeof(float); i++) {
        float a = ((float*)outputData)[i];
        float b = ((float*)goldenData)[i];
        float ae = std::abs(a - b);
        float re = ae / abs(b);
        if (ae > EPS && re > EPS) {
            printf("CompareResult index %d failed output is %lf, golden is %lf\n", i, a, b);
            wrongNum++;
        }
        if (wrongNum > maxPrintNums) {
            break;
        }
    }
#ifdef ASCENDC_CPU_DEBUG
    AscendC::GmFree((void*)goldenData);
#else
    CHECK_ACL(aclrtFreeHost(goldenData));
#endif
    return wrongNum;
}
} // MatmulCustomMian

int32_t main(int32_t argc, char* argv[])
{
    constexpr TestcaseParams caseParams = {24, 24 * 256, 480, 320, true};

    const char* socVersion = SOC_VERSION;
    auto ascendcPlatform = platform_ascendc::PlatformAscendCManager::GetInstance(socVersion);

    constexpr uint32_t blockDim = caseParams.blockDim;
    constexpr uint32_t M = caseParams.m;
    constexpr uint32_t N = caseParams.n;
    constexpr uint32_t K = caseParams.k;
    constexpr bool isBias = caseParams.isBias;

    size_t aFileSize = static_cast<size_t>(sizeof(uint16_t) * M * K);
    size_t bFileSize = static_cast<size_t>(sizeof(uint16_t) * K * N);
    size_t biasFileSize = static_cast<size_t>(sizeof(float) * N);
    size_t cFileSize = static_cast<size_t>(sizeof(float) * M * N);
    size_t userWorkspaceSize = 0;
    size_t systemWorkspaceSize = static_cast<size_t>(ascendcPlatform->GetLibApiWorkSpaceSize());
    size_t workspaceSize = userWorkspaceSize + systemWorkspaceSize;
    size_t tilingFileSize = sizeof(TCubeTiling);
    int64_t wrongNum = 0;

#ifdef ASCENDC_CPU_DEBUG
    uint8_t* a1 = (uint8_t *)AscendC::GmAlloc(aFileSize);
    uint8_t* b1 = (uint8_t *)AscendC::GmAlloc(bFileSize);
    uint8_t* a2 = (uint8_t *)AscendC::GmAlloc(aFileSize);
    uint8_t* b2 = (uint8_t *)AscendC::GmAlloc(bFileSize);
    uint8_t* bias = (uint8_t *)AscendC::GmAlloc(biasFileSize);
    uint8_t* c1 = (uint8_t *)AscendC::GmAlloc(cFileSize);
    uint8_t* c2 = (uint8_t *)AscendC::GmAlloc(cFileSize);
    uint8_t* workspace = (uint8_t *)AscendC::GmAlloc(workspaceSize);
    uint8_t* tiling = (uint8_t *)AscendC::GmAlloc(tilingFileSize);

    ReadFile("../input/a1_gm.bin", aFileSize, a1, aFileSize);
    ReadFile("../input/b1_gm.bin", bFileSize, b1, bFileSize);
    ReadFile("../input/a2_gm.bin", aFileSize, a2, aFileSize);
    ReadFile("../input/b2_gm.bin", bFileSize, b2, bFileSize);
    ReadFile("../input/bias_gm.bin", biasFileSize, bias, biasFileSize);
    MatmulA2B2ShareTiling::GenerateTiling(socVersion, caseParams, tiling);
    memcpy_s(tiling, tilingFileSize, tiling, tilingFileSize);

    ICPU_RUN_KF(matmul_a2_b2_share_custom, blockDim, a1, b1, a2, b2, bias, c1, c2, workspace, tiling);

    WriteFile("../output/output_1.bin", c1, cFileSize);
    WriteFile("../output/output_2.bin", c2, cFileSize);

    wrongNum = MatmulCustomMian::CompareResult(c1, cFileSize, "../output/output_1.bin");
    wrongNum += MatmulCustomMian::CompareResult(c2, cFileSize, "../output/output_2.bin");

    AscendC::GmFree((void*)a1);
    AscendC::GmFree((void*)b1);
    AscendC::GmFree((void*)a2);
    AscendC::GmFree((void*)b2);
    AscendC::GmFree((void*)bias);
    AscendC::GmFree((void*)c1);
    AscendC::GmFree((void*)c2);
    AscendC::GmFree((void*)workspace);
    AscendC::GmFree((void*)tiling);
#else
    CHECK_ACL(aclInit(nullptr));
    aclrtContext context;
    int32_t deviceId = 0;
    CHECK_ACL(aclrtSetDevice(deviceId));
    CHECK_ACL(aclrtCreateContext(&context, deviceId));
    aclrtStream stream = nullptr;
    CHECK_ACL(aclrtCreateStream(&stream));

    uint8_t* a1Host;
    uint8_t* a1Device;
    CHECK_ACL(aclrtMallocHost((void **)(&a1Host), aFileSize));
    CHECK_ACL(aclrtMalloc((void **)&a1Device, aFileSize, ACL_MEM_MALLOC_HUGE_FIRST));
    ReadFile("../input/a1_gm.bin", aFileSize, a1Host, aFileSize);
    CHECK_ACL(aclrtMemcpy(a1Device, aFileSize, a1Host, aFileSize, ACL_MEMCPY_HOST_TO_DEVICE));

    uint8_t* b1Host;
    uint8_t* b1Device;
    CHECK_ACL(aclrtMallocHost((void **)(&b1Host), bFileSize));
    CHECK_ACL(aclrtMalloc((void **)&b1Device, bFileSize, ACL_MEM_MALLOC_HUGE_FIRST));
    ReadFile("../input/b1_gm.bin", bFileSize, b1Host, bFileSize);
    CHECK_ACL(aclrtMemcpy(b1Device, bFileSize, b1Host, bFileSize, ACL_MEMCPY_HOST_TO_DEVICE));

    uint8_t* a2Host;
    uint8_t* a2Device;
    CHECK_ACL(aclrtMallocHost((void **)(&a2Host), aFileSize));
    CHECK_ACL(aclrtMalloc((void **)&a2Device, aFileSize, ACL_MEM_MALLOC_HUGE_FIRST));
    ReadFile("../input/a2_gm.bin", aFileSize, a2Host, aFileSize);
    CHECK_ACL(aclrtMemcpy(a2Device, aFileSize, a2Host, aFileSize, ACL_MEMCPY_HOST_TO_DEVICE));

    uint8_t* b2Host;
    uint8_t* b2Device;
    CHECK_ACL(aclrtMallocHost((void **)(&b2Host), bFileSize));
    CHECK_ACL(aclrtMalloc((void **)&b2Device, bFileSize, ACL_MEM_MALLOC_HUGE_FIRST));
    ReadFile("../input/b2_gm.bin", bFileSize, b2Host, bFileSize);
    CHECK_ACL(aclrtMemcpy(b2Device, bFileSize, b2Host, bFileSize, ACL_MEMCPY_HOST_TO_DEVICE));

    uint8_t* biasHost;
    uint8_t* biasDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&biasHost), biasFileSize));
    CHECK_ACL(aclrtMalloc((void **)&biasDevice, biasFileSize, ACL_MEM_MALLOC_HUGE_FIRST));
    ReadFile("../input/bias_gm.bin", biasFileSize, biasHost, biasFileSize);
    CHECK_ACL(aclrtMemcpy(biasDevice, biasFileSize, biasHost, biasFileSize, ACL_MEMCPY_HOST_TO_DEVICE));

    uint8_t* workspaceHost;
    uint8_t* workspaceDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&workspaceHost), workspaceSize));
    CHECK_ACL(aclrtMalloc((void **)&workspaceDevice, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST));

    uint8_t* tilingHost;
    uint8_t* tilingDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&tilingHost), tilingFileSize));
    CHECK_ACL(aclrtMalloc((void **)&tilingDevice, tilingFileSize, ACL_MEM_MALLOC_HUGE_FIRST));
    MatmulA2B2ShareTiling::GenerateTiling(socVersion, caseParams, tilingHost);
    CHECK_ACL(aclrtMemcpy(tilingHost, tilingFileSize, tilingHost, tilingFileSize, ACL_MEMCPY_HOST_TO_HOST));
    CHECK_ACL(aclrtMemcpy(tilingDevice, tilingFileSize, tilingHost, tilingFileSize, ACL_MEMCPY_HOST_TO_DEVICE));

    uint8_t* c1Host;
    uint8_t* c1Device;
    CHECK_ACL(aclrtMallocHost((void **)(&c1Host), cFileSize));
    CHECK_ACL(aclrtMalloc((void **)&c1Device, cFileSize, ACL_MEM_MALLOC_HUGE_FIRST));

    uint8_t* c2Host;
    uint8_t* c2Device;
    CHECK_ACL(aclrtMallocHost((void **)(&c2Host), cFileSize));
    CHECK_ACL(aclrtMalloc((void **)&c2Device, cFileSize, ACL_MEM_MALLOC_HUGE_FIRST));

    matmul_a2_b2_share_custom_do(blockDim, stream, a1Device, b1Device, a2Device, b2Device, biasDevice, c1Device, c2Device,
        workspaceDevice, tilingDevice);
    CHECK_ACL(aclrtSynchronizeStream(stream));

    CHECK_ACL(aclrtMemcpy(c1Host, cFileSize, c1Device, cFileSize, ACL_MEMCPY_DEVICE_TO_HOST));
    WriteFile("../output/output_1.bin", c1Host, cFileSize);
    CHECK_ACL(aclrtMemcpy(c2Host, cFileSize, c2Device, cFileSize, ACL_MEMCPY_DEVICE_TO_HOST));
    WriteFile("../output/output_2.bin", c2Host, cFileSize);

    wrongNum = MatmulCustomMian::CompareResult(c1Host, cFileSize, "../output/output_1.bin");
    wrongNum += MatmulCustomMian::CompareResult(c2Host, cFileSize, "../output/output_2.bin");

    CHECK_ACL(aclrtFree(a1Device));
    CHECK_ACL(aclrtFreeHost(a1Host));
    CHECK_ACL(aclrtFree(b1Device));
    CHECK_ACL(aclrtFreeHost(b1Host));

    CHECK_ACL(aclrtFree(a2Device));
    CHECK_ACL(aclrtFreeHost(a2Host));
    CHECK_ACL(aclrtFree(b2Device));
    CHECK_ACL(aclrtFreeHost(b2Host));

    CHECK_ACL(aclrtFree(biasDevice));
    CHECK_ACL(aclrtFreeHost(biasHost));

    CHECK_ACL(aclrtFree(c1Device));
    CHECK_ACL(aclrtFreeHost(c1Host));
    CHECK_ACL(aclrtFree(c2Device));
    CHECK_ACL(aclrtFreeHost(c2Host));

    CHECK_ACL(aclrtFree(workspaceDevice));
    CHECK_ACL(aclrtFreeHost(workspaceHost));

    CHECK_ACL(aclrtFree(tilingDevice));
    CHECK_ACL(aclrtFreeHost(tilingHost));

    CHECK_ACL(aclrtDestroyStream(stream));
    CHECK_ACL(aclrtDestroyContext(context));
    CHECK_ACL(aclrtResetDevice(deviceId));
    CHECK_ACL(aclFinalize());
#endif
    if (wrongNum != 0) {
        printf("test failed!\n");
    } else {
        printf("test pass!\n");
    }
    return 0;
}